//
//  receiveBigHeadImage.m
//  tcpoctest
//
//  Created by apple on 13-8-5.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "receiveBigHeadImage.h"

#import "LocalPathDataSource.h"
#import "bigHeadImageDataSource.h"
#import "BigImageInfo.h"
#import "bigimagedb.h"

@implementation receiveBigHeadImage

-(void)processreceive
{
    NSString *mail = [logicsb ReadUnencodeString];
    
    if ([[DataControl shareControl].bigHIDS.bigimageRequestSet containsObject:mail] ) {
        if ([logicsb ReadChar] == 1) {
            NSString *url = [logicsb ReadUnencodeString];
            NSLog(@"hi url %@",url);
            NSData  *imagedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            
            if ([imagedata length] == 0) {
                return;
            }
            
            NSString *strname = getFileNameWithDate(FT_HEADIMAGE);
            strname = [NSString stringWithFormat:@"%@%@",strname,mail];
            NSString *urlpath = @"";
            urlpath =[[[DataControl shareControl].localpathds LPHeadImagePath]
                      stringByAppendingPathComponent:strname];
            BOOL bsuccess = [imagedata writeToFile:urlpath atomically:YES];
            
            if (bsuccess == NO) {
                return;
            }
            
            BigImageInfo *binfo = [[DataControl shareControl].bigHIDS.bigimageDic objectForKey:mail];
            if (binfo == nil) {
                binfo = [[BigImageInfo alloc] init];
                binfo.mail = mail;
                binfo.url = urlpath;
                NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
                binfo.updatetime = [dat timeIntervalSince1970];
                
                [[DataControl shareControl].bigHIDS.bigimageDic setObject:binfo forKey:binfo.mail];
            }
            else
            {
                [[FileManager shareControl] deleteFile:binfo.url];
                binfo.url = urlpath;
                NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
                binfo.updatetime = [dat timeIntervalSince1970];
            }
            
            [[DataBaseCtrol shareControl].bigimagedatabase insertBigInfo:binfo];
            
            [[DataControl shareControl] UpdateImageWithMail:binfo.mail
                                                  withImage:
             OriginImage([UIImage imageWithData:imagedata], CGSizeMake(BIG_HEAD_IMAGE, BIG_HEAD_IMAGE))];
            
            [[DataControl shareControl].UICommendDS addUICommand:UC_READBIGSUCCESS];
            
            [[DataControl shareControl].UICommendDS addUICommand:UC_REFRESHCURVIEW];
        }
        
        [[DataControl shareControl].bigHIDS.bigimageRequestSet removeObject:mail];

    }
    
    [self ShowLog];
    
}

@end
